import * as vscode from 'vscode';
import { HiLogService, LogLevel } from './HiLogService';

export class HiLogViewProvider implements vscode.WebviewViewProvider {
    public static readonly viewType = 'hiLogView';
    private webviewView?: vscode.WebviewView;
    private disposables: vscode.Disposable[] = [];
    // private hiLogService: HiLogService;

    constructor(private readonly _extensionUri: vscode.Uri) {
        // this.hiLogService = HiLogService.getInstance();
    }

    resolveWebviewView(
        webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        _token: vscode.CancellationToken
    ) {

        this.webviewView = webviewView;

        // Configure webview
        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [vscode.Uri.joinPath(this._extensionUri, 'webview-ui', 'dist')]
        };

        // Initial HTML content
        webviewView.webview.html = this.getHtmlForWebview(webviewView.webview);

        // // Set up message handling
        // this.setupMessageHandling(webviewView);

        // // Subscribe to log updates from HiLogService
        // const logUpdateDisposable = this.hiLogService.onLogUpdate((log) => {
        //     if (this.webviewView) {
        //         this.webviewView.webview.postMessage({ 
        //             command: 'addLogs', 
        //             logs: log 
        //         });
        //     }
        // });

        // // Start device monitoring
        // this.hiLogService.startDeviceMonitoring();

        // // Store disposables
        // this.disposables.push(
        //     logUpdateDisposable,
        //     webviewView.onDidDispose(() => {
        //         // Clean up when the webview is closed
        //         this.disposables.forEach(d => d.dispose());
        //         this.disposables = [];
        //     })
        // );
    }

    // private setupMessageHandling(webviewView: vscode.WebviewView) {
    //     webviewView.webview.onDidReceiveMessage(
    //         message => {
    //             switch (message.command) {
    //                 case 'showHiLog':
    //                     vscode.commands.executeCommand('hiLogView.focus');
    //                     break;
    //                 case 'clearLogs':
    //                     this.hiLogService.clearLogBuffer();
    //                     break;
    //                 case 'changeLogLevel':
    //                     // 处理日志级别变更
    //                     const newLevel = message.level as LogLevel;
    //                     if (Object.values(LogLevel).includes(newLevel)) {
    //                         this.hiLogService.setLogLevel(newLevel);
    //                         // 清空日志缓冲区以避免混淆不同级别的日志
    //                         this.hiLogService.clearLogBuffer();
    //                         // 通知WebView日志级别已更改
    //                         if (this.webviewView) {
    //                             this.webviewView.webview.postMessage({
    //                                 command: 'logLevelChanged',
    //                                 level: newLevel
    //                             });
    //                         }
    //                     }
    //                     break;
    //             }
    //         },
    //         undefined,
    //         this.disposables
    //     );
    // }

    private getNonce() {
		let result = '';
		const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		const charactersLength = characters.length;
		for (let i = 0; i < 32; i++) {
			result += characters.charAt(Math.floor(Math.random() * charactersLength));
		}
		return result;
	}
    private getHtmlForWebview(webview: vscode.Webview) {
		// Get the local path to main script run in the webview
		const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'webview-ui', 'dist', 'assets', 'index.js'));
		
		// Get the local path to css styles
		const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'webview-ui', 'dist', 'assets', 'index.css'));
		
		// Use a nonce to only allow specific scripts to be run
		const nonce = this.getNonce();

		return `<!DOCTYPE html>
			<html lang="en" class="dark">
			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width, initial-scale=1.0">
				<title>HiLog</title>
				<link href="${styleUri}" rel="stylesheet">
				<script nonce="${nonce}">
					// Set initial route for the Vue app
					window.initialRoute = '#/hilog';
					// Setup VSCode API access
					const vscode = acquireVsCodeApi();
					window.vscode = vscode;
				</script>
			</head>
			<body>
				<div id="app"></div>
				<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
			</body>
			</html>`;
	}
}